package dht.server;

import dht.IDataServer;
import dht.IDataServerRouteTable;
import dht.IRoutineHandler;
import dht.IStorage;
import dht.ITransactionHandler;
import dht.entity.Message;
import dht.entity.NodeInfo;
import dht.socket.SocketHandler;
import dht.storage.StorageImpl;
import dht.table.DataServerRouteTableImpl;
import dht.throwable.DhtException;

public class DataServerImpl extends AbstractServer implements IDataServer {

	protected IDataServerRouteTable routeTable;
	protected IStorage storage;

	public DataServerImpl(NodeInfo localInfo, NodeInfo masterInfo) {
		super(localInfo);
		this.routeTable = new DataServerRouteTableImpl(masterInfo);
		this.storage = new StorageImpl();
	}

	@Override
	public void startServer() throws DhtException {
		new Thread(this).start();
		IRoutineHandler routineHandler = new DataServerRoutineHandlerImpl(this,
				routeTable);
		new Thread(routineHandler).start();
	}

	@Override
	public void handleInitiativeTransaction(NodeInfo nodeInfo, Message msg,
			boolean isSync) throws DhtException {
		ITransactionHandler transactionHandler = new DataServerTransactionHandlerImpl(
				localInfo, nodeInfo, routeTable, this, tcpConnection, storage);
		transactionHandler.handleInitiativeTransaction(msg, isSync);
	}

	@Override
	public void handlePassiveTransaction(SocketHandler socketHandler,
			boolean isSync) throws DhtException {
		ITransactionHandler transactionHandler = new DataServerTransactionHandlerImpl(
				localInfo, socketHandler, routeTable, this, tcpConnection,
				storage);
		transactionHandler.handlePassiveTransaction(isSync);
	}

	@Override
	public void setRouteTable(IDataServerRouteTable routeTable) {
		this.routeTable = routeTable;
	}

}
